package net.xdclass.onlinexdclass.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.xdclass.onlinexdclass.model.entity.User;
import net.xdclass.onlinexdclass.service.impl.UserServiceImpl;
import net.xdclass.onlinexdclass.utils.JsonDate;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//拦截所有pri结尾的请求，进行判断
//@WebFilter(urlPatterns = "/api/v1/pri/*", filterName = "loginFilter")
public class LoginFilter implements Filter {


    public static final ObjectMapper objectMapper = new ObjectMapper();


    /**
     * 容器加载的时候自动调用
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter");

        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;


        HttpServletResponse servletResponse1 = (HttpServletResponse) servletResponse;


        String token = httpServletRequest.getHeader("token");
        if(StringUtils.isEmpty(token)) {
            token = httpServletRequest.getParameter("token");


        }

        if(!StringUtils.isEmpty(token)) {
            //判断token是否合法 TODO
            User user = UserServiceImpl.sessionMap.get(token);
            if(null != user) {
                //如果不等于null，就可以放行
                filterChain.doFilter(servletRequest,servletResponse);
            } else {
                JsonDate jsonDate = JsonDate.bulidError("登陆失败", -2);
                String jsonString = objectMapper.writeValueAsString(jsonDate);
                render(servletResponse1, jsonString);
            }

        } else {
            JsonDate jsonDate = JsonDate.bulidError("未登陆", -3);
            String jsonString = objectMapper.writeValueAsString(jsonDate);
            render(servletResponse1, jsonString);
        }


    }


    /**
     * 自定义Filter未登陆json错误码提示开发
     */
    public void render(HttpServletResponse response, String json) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        try(PrintWriter printWriter = response.getWriter()) {

            printWriter.write(json);


        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     * 容器销毁的时候
     */
    @Override
    public void destroy() {
        System.out.println("destroy LoginFilter");
    }
}
